package com.qg.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.qg.common.Constants;
import com.qg.dto.ReturnResult;
import com.qg.dto.ReturnResultUtils;
import com.qg.exception.GoodsException;
import com.qg.pojo.QgGoods;
import com.qg.pojo.QgGoodsTempStock;
import com.qg.pojo.QgUser;
import com.qg.utils.EmptyUtils;
import com.qg.utils.IdWorker;
import com.qg.utils.RedisUtil;
import com.qg.vo.GoodsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class LocalGoodsServiceImpl implements LocalGoodsService{
    @Reference
    private QgGoodsService qgGoodsService;
    @Reference
    private QgGoodsTempStockService qgGoodsTempStockService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public ReturnResult queryGoodsById(String id) throws Exception {
        GoodsVo goodsVo=null;
        //1、首先从redis中进行获取
        //2、redis中没有，则走数据库查询，并将结果写入到redis
        //3、redis中有，则走redis
        String goodsVoJson=redisUtil.getStr(Constants.goodsPrefix+id);
        if (EmptyUtils.isEmpty(goodsVoJson)){
            goodsVo=new GoodsVo();
            QgGoods qgGoods=qgGoodsService.getQgGoodsById(id);
            BeanUtils.copyProperties(qgGoods,goodsVo);
            //获取库存信息
            //1、获取临时库存表，goods_id 为id的有效的记录数->用户已消费或待消费记录数 100 activeCount
            Map<String,Object> param=new HashMap<String, Object>();
            param.put("goodsId",id);
            param.put("active",1);
            Integer activeCount=qgGoodsTempStockService.getQgGoodsTempStockCountByMap(param);
            //实际库存
            Integer currentCount=goodsVo.getStock()-activeCount;
            goodsVo.setCurrentStock(currentCount);
            //放在redis当中
            redisUtil.setStr(Constants.goodsPrefix+id, JSONObject.toJSONString(goodsVo));
        }else {
            goodsVo=JSONObject.parseObject(goodsVoJson,GoodsVo.class);
        }
        return ReturnResultUtils.returnSuccess(goodsVo);
    }

    @Override
    public ReturnResult getGoods(String token, String goodsId) throws Exception {
        //1、根据token知道是哪个用户 获取用户信息
        String userJson=redisUtil.getStr(token);
        QgUser qgUser= JSONObject.parseObject(userJson,QgUser.class);
        //2、查看用户是否已经抢购过该商品，如果用户有抢购成功未支付的或已经支付成功的记录，则不能抢
        Map<String,Object> param=new HashMap<String, Object>();
        param.put("goodsId",goodsId);
        param.put("active",1);
        param.put("userId",qgUser.getId());
        Integer activeCount=qgGoodsTempStockService.getQgGoodsTempStockCountByMap(param);
        if (activeCount>0){
            return ReturnResultUtils.returnFail(GoodsException.USER_REPEAT_GET.getCode(),GoodsException.USER_REPEAT_GET.getMessage());
        }
        //3、判断库存是否大于0，如果大于0则进入抢购环节
        String goodsVoJson=redisUtil.getStr(Constants.goodsPrefix+goodsId);
        GoodsVo goodsVo=JSONObject.parseObject(goodsVoJson,GoodsVo.class);
        if (goodsVo.getCurrentStock()<=0){
            return ReturnResultUtils.returnFail(GoodsException.GOODS_IS_CLEAR.getCode(),GoodsException.GOODS_IS_CLEAR.getMessage());
        }
        //4、更新库存 包括 更新临时库存表（插入记录）以及更新redis数据
        QgGoodsTempStock qgGoodsTempStock=new QgGoodsTempStock();
        qgGoodsTempStock.setId(IdWorker.getId());
        qgGoodsTempStock.setUserId(qgUser.getId());
        qgGoodsTempStock.setCreatedTime(new Date());
        qgGoodsTempStock.setGoodsId(goodsVo.getId());
        qgGoodsTempStock.setStatus(Constants.StockStatus.lock);
        qgGoodsTempStock.setUpdatedTime(new Date());
        qgGoodsTempStockService.qdtxAddQgGoodsTempStock(qgGoodsTempStock);
        goodsVo.setCurrentStock(goodsVo.getCurrentStock()-1);//当前库存减一
        redisUtil.setStr(Constants.goodsPrefix+goodsId,JSONObject.toJSONString(goodsVo));
        //5、生成订单
        //6、返回执行结果
        return ReturnResultUtils.returnSuccess();
    }
}
